import 'dart:async';
import 'dart:math';

import 'package:flame/events.dart';
import 'package:flame/game.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

import 'Bullet.dart';
import 'EndGame.dart';
import 'MainCircle.dart';
import 'PauseMenu.dart';
import 'TextCom.dart';


class MyGame extends FlameGame with PanDetector {
  final Path path = Path();
  final Paint paint = Paint()..color = Color.fromARGB(255, 134, 169, 238);
  final Paint paintMenu = Paint()..color = Color.fromARGB(255, 231, 142, 24);
  late MainCircle mainCircle;
  List<Bullet> bullets = [];
  bool isRunning = true;
  double seconds = 0;
  late TextCom txt;
  late TextCom restartTxt;
  late TextCom menuTxt;
  late Rect rect;
  late double counts = 0;
  late final gameController;

  @override
  Future<void> onLoad() async {
    gameController = Get.put<GameController>(GameController());
    gameController.gameEnd();
    mainCircle =
        MainCircle(position: Vector2(canvasSize.x / 2, canvasSize.y / 2));
    path.addRect(Rect.fromLTWH(0, 0, canvasSize.x, canvasSize.y));
    add(mainCircle);
    txt = TextCom(position: Vector2(40, 40), text: '0');
    rect = Rect.fromPoints(Vector2(canvasSize.x - 110, 10).toOffset(),
        Vector2(canvasSize.x - 10, 70).toOffset());
    menuTxt = TextCom(
        position: Vector2(canvasSize.x - 60, 35), text: '菜单', textSize: 30);
    return super.onLoad();
  }

  @override
  void render(Canvas canvas) {
    super.render(canvas);
    canvas.drawPath(path, paint);
    canvas.drawRect(rect, paintMenu);
    mainCircle.render(canvas);
    txt.render(canvas);
    menuTxt.render(canvas);
    for (var bullet in bullets) {
      bullet.render(canvas);
    }
  }

  void toggleGameState() {
    pauseEngine();
    overlays.add(PauseMenu.menuId);
  }

  void createBullet() {
    /// 随机半径
    var radius = Random().nextInt(10) + 5;

    /// 计算位置
    /// 是否在水平方向上，即画布的顶部和底部
    bool isHorizontal = Random().nextBool();
    int x = isHorizontal
        ? Random().nextInt(canvasSize.x.toInt())
        : Random().nextBool()
            ? radius
            : canvasSize.x.toInt() - radius;
    int y = isHorizontal
        ? Random().nextBool()
            ? radius
            : canvasSize.y.toInt() - radius
        : Random().nextInt(canvasSize.y.toInt());
    var position = Vector2(x.toDouble(), y.toDouble());

    /// 计算角度
    var angle = atan2(y - mainCircle.position.y, x - mainCircle.position.x);

    /// 计算速度
    double speed = seconds / 10 + 5;
    bullets.add(Bullet(
        position: position,
        angle: angle,
        radius: radius.toDouble(),
        speed: speed));
  }

  @override
  void onGameResize(Vector2 gameSize) {
    super.onGameResize(gameSize);
  }

  double time = 0;
  double countTime = 0;
  double timeDe = 0.5;

  @override
  void update(double dt) {
    super.update(dt);
    countTime += dt;
    if (countTime >= 1) {
      gameController.increment();
      counts++;
      txt.text = '$counts';
      countTime = 0;
    }
    for (var bullet in bullets) {
      bullet.update(dt);
    }
    //timeDe = seconds / 10;
    Function schedule = () {
      time += dt;
      if (time >= timeDe) {
        createBullet();
        time = 0;
      }
    };

    if (isRunning) {
      seconds += dt;
      schedule();
      for (var bullet in bullets) {
        if (collisionCheck(bullet)) {
          stop();
          return;
        } else {
          bullet.update(dt);
        }
      }
    }
  }

  bool collisionCheck(Bullet bullet) {
    var tempPath =
        Path.combine(PathOperation.intersect, mainCircle.path, bullet.path);
    return tempPath.getBounds().width > 0;
  }

  void stop() {
    for (var bullet in bullets) {
      bullet.isStopMove(false);
    }
    isRunning = false;
    pauseEngine();
    overlays.add(EndGame.menuId);
    //Timer(5.seconds, () { reStart(); });
  }

  bool isPan = false;
  @override
  void onPanStart(DragStartInfo info) {
    isPan = false;
    if (mainCircle.path.contains(info.eventPosition.game.toOffset())) {
      isPan = true;
    }

    if (rect.contains(info.eventPosition.global.toOffset())) {
      print('点到了');
      toggleGameState();
    }
  }

  @override
  void onPanCancel() {
    isPan = false;
  }

  @override
  void onPanUpdate(DragUpdateInfo info) {
    var eventPosition = info.eventPosition.game;
    if (eventPosition.x < mainCircle.radius) {
      eventPosition.x = mainCircle.radius;
    }
    if (eventPosition.x > canvasSize.x - mainCircle.radius) {
      eventPosition.x = canvasSize.x - mainCircle.radius;
    }
    if (eventPosition.y < mainCircle.radius) {
      eventPosition.y = mainCircle.radius;
    }
    if (eventPosition.y > canvasSize.y - mainCircle.radius) {
      eventPosition.y = canvasSize.y - mainCircle.radius;
    }

    if (isPan) {
      mainCircle.onPanUpdate(eventPosition);
    }
  }
}

class GameController extends GetxController {
  var score = 0.obs;
  void increment() {
    score++;
  }

  void gameEnd() {
    score = 0.obs;
  }
}
